//
//  CollectListViewController.m
//  MedicineBox
//
//  Created by dllo on 15/8/28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "CollectListViewController.h"
#import "CollectListCollectionViewCell.h"
#import "MedicineBoxDataBase.h"
#import "MJRefreshNormalHeader.h"
#import "DrugDetailViewController.h"
#import "DKNightVersion.h"
#import "HomeModel.h"
#import "SearchPurchaseController.h"

@interface CollectListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UICollectionView *collectView;
@property (nonatomic, retain) NSArray *collectArray;
@property (nonatomic, retain) UILabel *prompt;
@property (nonatomic, retain) UITabBarController *tab;
@property (nonatomic, retain) UINavigationController *nav;

@end

@implementation CollectListViewController

-(void)dealloc
{
    [_collectView release];
    [_collectArray release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectArray = [NSArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    [self createNavigation];
    [self createCollectView];
    
    

}
- (void)viewDidAppear:(BOOL)animated
{
    [self createQueue];
}

#pragma mark -
#pragma mark 设置导航栏
- (void)createNavigation
{
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 30, 100, 30)];
    titleLabel.text = @"我的收藏";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.nightBackgroundColor = [UIColor colorWithRed:0.3 green:0.5 blue:0.3 alpha:1];
    titleLabel.nightTextColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10 , 30, 60, 30)];
    
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [backButton release];
    
}

- (void)buttonAction:(id)sender
{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark -
#pragma mark 查询数据库信息
- (void)createQueue
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [MedicineBoxDataBase selectAll];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.collectArray = array;
            [self.collectView reloadData];
            
            
            if (self.collectArray.count == 0) {
                self.prompt = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 100, 100, 50)];
                [self.collectView addSubview: self.prompt];
                self.prompt.text = @"您还没有收藏药品";
                self.prompt.numberOfLines = 2;
                self.prompt.textColor = [UIColor redColor];
                self.prompt.textAlignment = NSTextAlignmentCenter;
            }else
            {
                [self.prompt removeFromSuperview];
                
            }

        });
    });
}

#pragma mark -
#pragma mark 创建collectView
- (void)createCollectView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 70, self.view.frame.size.width - 20, self.view.frame.size.height - 70)
        collectionViewLayout:layout];
    [self.view addSubview:self.collectView];
    self.collectView.backgroundColor = [UIColor whiteColor];
    self.collectView.dataSource = self;
    self.collectView.delegate = self;
    [self.collectView registerClass:[CollectListCollectionViewCell class] forCellWithReuseIdentifier:@"collectCell"];
    
    self.collectView.nightBackgroundColor = UIColorFromRGB(0x343434);
    
    [layout release];
    [_collectView release];
    
    // 刷新
    self.collectView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self.collectView.header beginRefreshing];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.collectView reloadData];
            // 结束刷新
            [self.collectView.header endRefreshing];
        });
        
        
    }];

    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectCell" forIndexPath:indexPath];
    [cell valueWithModel:[self.collectArray objectAtIndex:indexPath.item]];
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.view.frame.size.width - 50) / 2, 200);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeModel *model = [self.collectArray objectAtIndex:indexPath.item];
    if ([model.type isEqualToString:@"her"]) {
        
        DrugDetailViewController *detail = [[DrugDetailViewController alloc] init];
        detail.deatilId = model._id;
        detail.namecn = model.namecn;
        
        [self presentViewController:detail animated:YES completion:nil];
        [detail release];
        
    } else if ([model.type isEqualToString:@"mine"]) {
    
       
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model._id,@"id",model.titleimg,@"img",model.avgprice,@"price",model.namecn,@"name", nil];
        
        NSString *str = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getbaseinfo&itemcode=%@&flag=0&province=9&encryptversion=2&sign=01DE5C022E6E01EF39A79B2A4569D308&timestamp=20150918190726&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",model._id];
        SearchPurchaseController *searchPC = [[SearchPurchaseController alloc] init];
        self.tab.tabBar.hidden = YES;
        [searchPC getSearchUrl:str tab:self.tabBarController nav:self.navigationController dic:dic];
        [self.navigationController pushViewController:searchPC animated:YES];
        [searchPC release];
    
    }
  
}

- (void)getTab:(UITabBarController *)tabC navC:(UINavigationController *)navC
{

    self.tab = tabC;
    self.nav = navC;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


@end
